package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.utils.Spatial4jUtil;
import com.baichang.taoshunda.dao.BussinessDao;
import com.baichang.taoshunda.dao.CouponDao;
import com.baichang.taoshunda.dao.FavoritesDao;
import com.baichang.taoshunda.dao.PromotionDao;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.Favorites;
import com.baichang.taoshunda.service.FavoritesService;
import com.baichang.taoshunda.service.ParamsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * Created by ${wushenglu} on 17/08/23.
 */
@Service
public class FavoritesServiceImpl implements FavoritesService {
    @Autowired
    private FavoritesDao favoritesDao;
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private PromotionDao promotionDao;
    @Autowired
    private BussinessDao bussinessDao;
    @Autowired
    private ParamsService paramsService;


    /**
     * 收藏商家
     * 武圣路
     * 接口
     *
     * @param bussId 商家编号
     * @param userId 用户编号
     * @param typeId 商家类别   1 商品商家  2   本地服务商家
     * @return
     */
    @Override
    public boolean favoriterBuss(int bussId, int userId, int typeId) throws ServiceException {
        int favoriterCount = favoritesDao.getCountByUserAndBusId(bussId, userId, typeId);
        if (favoriterCount == 0) {
            //收藏商家
            Favorites favorites = new Favorites();
            //用户编号
            favorites.setUserId(userId);
            //收藏时间
            favorites.setCreated(new Date());
            //收藏商家编号
            favorites.setFavoriteId(bussId);
            favorites.setTypeId(typeId);
            return favoritesDao.save(favorites) > 0;
        } else {
            favoritesDao.deleteByBussId(userId, bussId, typeId);
            return true;
        }

    }

    /**
     * 我的收藏列表
     *
     * @param ulat     纬度
     * @param ulng     经度
     * @param userId   用户编号
     * @param typeId   收藏类型
     * @param nowPage  当前页
     * @param pageSize @return
     */
    @Override
    public List<Map<String, Object>> myFavoites(double ulat, double ulng, int userId, int typeId, int nowPage, int pageSize) throws ServiceException {
        try {
            List<Map<String, Object>> mapList = favoritesDao.myFavoites(userId, typeId, nowPage, pageSize);
            if (mapList.size() == 0) {
                throw new ServiceException("当前收藏生活服务已下架");
            }
            for (int i = 0; i < mapList.size(); i++) {
                mapList.get(i).put("isFavorites", favoritesDao.getCountByUserAndBusId(Integer.parseInt(mapList.get(i).get("id").toString()), userId, typeId));
            }
            if (typeId != 3) {
                mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
                if (typeId == 1) {
                    for (int i = 0; i < mapList.size(); i++) {
                        //获取商家编号
                        int busId = Integer.parseInt(mapList.get(i).get("id").toString());
                        //遍历获取商家的优惠劵
                        List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
                        if (couponList.size() > 0) {
                            mapList.get(i).put("couponList", couponList);
                        }
                        //遍历获取商家的优惠活动
                        List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
                        if (promotionList.size() > 0) {
                            mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
                        } else {
                            mapList.get(i).put("promotionList", "");
                        }
                        Map item = mapList.get(i);
                        BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                        double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                        item.put("dispatching", dispatching);
                    }
                }
            }

            return mapList;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public int getCountByUserAndBusId(int bussId, int userId, int typeId) {
        return favoritesDao.getCountByUserAndBusId(bussId, userId, typeId);
    }

    @Override
    public Map<String, Object> myFavoitesPc(double ulat, double ulng, int userId, int typeId, int nowPage, int pageSize) {
        try {
            List<Map<String, Object>> mapList = favoritesDao.myFavoites(userId, typeId, nowPage, pageSize);
            int total = favoritesDao.getTotal(userId, typeId);
            mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
            if (typeId == 1) {
                for (int i = 0; i < mapList.size(); i++) {
                    //获取商家编号
                    int busId = Integer.parseInt(mapList.get(i).get("id").toString());
                    //遍历获取商家的优惠劵
                    List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
                    mapList.get(i).put("couponList", couponList);
                    //遍历获取商家的优惠活动
                    int promotionCount = promotionDao.getPromotionCountByBussId(busId);
                    if (promotionCount > 0) {
                        List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
                        mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
                    } else {
                        mapList.get(i).put("promotionList", "");
                    }

                }
            }
            for (int i = 0; i < mapList.size(); i++) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
                mapList.get(i).put("isFavorites", favoritesDao.getCountByUserAndBusId(Integer.parseInt(mapList.get(i).get("id").toString()), userId, typeId));
            }


            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", mapList);
            map.put("total", total);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取配送费
     *
     * @param busId    商家编号
     * @param distance 距离
     * @return
     * @throws ServiceException
     */
    private double getDispatching(int busId, BigDecimal distance, Integer isFree) throws ServiceException {
        //获取商家信息
        Bussiness bussiness = bussinessDao.getEntityById(busId);
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        //查看商家是否免费配送
        int isDispatching = bussiness.getIsDispatching();
        //如果免费配送费为0
        if (isDispatching == 1 || isFree == 1) {
            return 0.0;
        } else {
            double qibuDistance = Double.parseDouble(paramsService.getParamsValue(31, 29).get("value").toString());
            //判断是否在起步范围内
            //不在起步内
            if (distance.doubleValue() > qibuDistance) {
                double paramsDistance = distance.doubleValue();
                double qibuMoney = Double.parseDouble(paramsService.getParamsValue(32, 30).get("value").toString());
                //超过起步距离每多少公里
                double passDiatance = Double.parseDouble(paramsService.getParamsValue(33, 31).get("value").toString());
                //超过起步距离每多少公里多少钱
                double passMoney = Double.parseDouble(paramsService.getParamsValue(34, 32).get("value").toString());
                double distance2 = paramsDistance - qibuDistance;
                //超出范围的次数
                double count = Math.floor(distance2 / passDiatance) + 1;
                return qibuMoney + passMoney * count;
            } else {
                //起步内返回起步价
                double qibuMoney = Double.parseDouble(paramsService.getParamsValue(32, 30).get("value").toString());
                return qibuMoney;
            }
        }

    }
}
